package grosso.thread;

import java.util.Map;
import java.util.Random;

import util.Storage;
import util.Table;

public class Modifier implements Runnable {

	private final Table table;
	private final int iterations;

	public Modifier(Table table, int iterations) {
		this.table = table;
		this.iterations = iterations;
	}
	
	@Override
	public void run() {
		try {
			modifySomeValues();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void modifySomeValues() throws InterruptedException {
		int temp = 0;
		while(temp < this.iterations) {
			 modifyValue();
			 temp++;
		}
	}

	public void modifyValue() {
		Map<Integer, Storage<String>> tempMap = table.getMap();
		synchronized (tempMap) {
			Random random = new Random();
			int randomKey = random.nextInt(tempMap.size());
			Storage<String> value = tempMap.get(randomKey);
			tempMap.put(randomKey, new Storage<String>(String.valueOf(Integer.valueOf(value.getValue()) + 1)));
		}
	}

}
